package com.hlyue.ingress.consecutiveportalhacking;

import android.content.Context;
import android.content.SharedPreferences;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.Seconds;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * Created by Richard on 2015/8/28.
 */
public class ConsecutiveHackingUtils {
    private final static String PREFERENCE = "CONSECUTIVE_HACKING_UTILS";
    private final static String KEY_FIRST = "KEY_FIRST";
    private final static String KEY_LAST = "KEY_LAST";

    private static SharedPreferences getSharedPreference(final Context context) {
        return context.getSharedPreferences(PREFERENCE, 0);
    }

    public static void doHacking(final Context context) {
        getSharedPreference(context).edit().putLong(KEY_LAST, System.currentTimeMillis()).apply();
        if (getSharedPreference(context).getLong(KEY_FIRST, 0L) == 0L)
            getSharedPreference(context).edit().putLong(KEY_FIRST, System.currentTimeMillis()).apply();
    }

    public static int getConsecutiveDays(final Context context) {
        long s = getSharedPreference(context).getLong(KEY_FIRST, System.currentTimeMillis());
        final DateTime sourceDate = new DateTime(s);
        final DateTime currentDate = DateTime.now();
        return Days.daysBetween(sourceDate, currentDate).getDays();
    }

    public static String getSourceDay(final Context context) {
        long s = getSharedPreference(context).getLong(KEY_FIRST, System.currentTimeMillis());
        return DateTimeFormat.forPattern("yy-mm-dd").print(s);
    }

    public static Seconds getPendingTime(final Context context) {
        long s = getSharedPreference(context).getLong(KEY_LAST, System.currentTimeMillis());
        long pending = s + 24*3600*1000 - System.currentTimeMillis();
        return Seconds.seconds((int) (pending / 1000));
    }
}
